class TestBreakable extends Test{

    public m_body1:Box2D.Dynamics.b2Body;
    public m_velocity:Box2D.Common.Math.b2Vec2 = new Box2D.Common.Math.b2Vec2();
    public m_angularVelocity:number;
    public m_shape1:Box2D.Collision.Shapes.b2PolygonShape = new Box2D.Collision.Shapes.b2PolygonShape();
    public m_shape2:Box2D.Collision.Shapes.b2PolygonShape = new Box2D.Collision.Shapes.b2PolygonShape();
    public m_piece1:Box2D.Dynamics.b2Fixture;
    public m_piece2:Box2D.Dynamics.b2Fixture;
    public m_broke:boolean;
    public m_break:boolean;

    public constructor(sprite:DebugDraw)
    {
        super(sprite);

        this.m_world.SetContactListener(new ContactListener1(this));

        let ground:Box2D.Dynamics.b2Body = this.m_world.GetGroundBody();

        //breakable dynamic body
        {
            let bd:Box2D.Dynamics.b2BodyDef = new Box2D.Dynamics.b2BodyDef();
            bd.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
            bd.position.Set(5.0,5.0);
            bd.angle = 0.25 * Math.PI;
            this.m_body1 = this.m_world.CreateBody(bd);
            this.m_shape1.SetAsOrientedBox(0.5,0.5, new Box2D.Common.Math.b2Vec2(-0.5, 0));
            this.m_piece1 = this.m_body1.CreateFixture2(this.m_shape1, 1.0);
            
            this.m_shape2.SetAsOrientedBox(0.5,0.5, new Box2D.Common.Math.b2Vec2(0.5, 0));
            this.m_piece2 = this.m_body1.CreateFixture2(this.m_shape2, 1.0); 
        }

        this.m_break = false;
        this.m_broke = false;
    }

    public Break():void
    {
        this.m_body1.SetLinearVelocity(this.m_velocity);
        this.m_body1.SetAngularVelocity(this.m_angularVelocity);

        let self = this;
        this.m_body1.Split(function(fixture:Box2D.Dynamics.b2Fixture):boolean{
            return fixture != self.m_piece1;
        })
    }

    public update():void
    {
        super.update();
        if(this.m_break)
        {
            this.Break();
            this.m_broke = true;
            this.m_break = false;
        }

        if(this.m_broke == false)
        {
            this.m_velocity = this.m_body1.GetLinearVelocity();
            this.m_angularVelocity = this.m_body1.GetAngularVelocity();
        }
    }
}

class ContactListener1 extends Box2D.Dynamics.b2ContactListener
{
    private test:TestBreakable;

    public constructor(test:TestBreakable){
        super();
        this.test = test;
    }

    public PostSolve(contact:Box2D.Dynamics.Contacts.b2Contact, impulse:Box2D.Dynamics.b2ContactImpulse):void
    {
        if(this.test.m_broke)
        {
            return;
        }
        let count:number = contact.GetManifold().m_pointCount;
        let maxImpulse:number = 0.0;
        //console.log(contact);
        for(var i:number = 0; i < count; i++)
        {
            maxImpulse = Box2D.Common.Math.b2Math.Max(maxImpulse, impulse.normalImpulses[i]);
        }

        if(maxImpulse > 50)
        {
            this.test.m_break = true;
        }
    }
}